package com.lupus.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.logging.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;
import com.lupus.business.Business;
import com.lupus.common.*;
import com.lupus.util.*;

public final class DownloadServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	static Logger logger = Logger.getLogger(ServiceServlet.class.getName());
	
	public void doGet(HttpServletRequest request,HttpServletResponse response){
		String downloadType = request.getParameter("downloadType");
		if("image".equals(downloadType)){
			downloadImage(request,response);
		}else if("file".equals(downloadType)){
			downloadFile(request,response);
		}else{
			downloadExcel(request,response);
		}
	}
	
	private void downloadExcel(HttpServletRequest request,HttpServletResponse response){
		Map currentUser  = (Map)request.getSession().getAttribute("currentUser");
		Map<String,Object> responseMap = new HashMap<String,Object>();
		try{
			String requestString = request.getParameter("requestString");
			requestString = requestString.replaceAll("<xml>","").replaceAll("</xml>","").replaceAll("#localLanguage#",request.getLocale().getLanguage());
			requestString = requestString.replaceAll("#currentUser#",currentUser==null?"":(String)currentUser.get("OID")).replaceAll("#currentTime#",DateUtil.getCurrentTime()).replaceAll("#currentIdentity#",IdentityUtil.getCurrentIdentity());
			Map<String,Object> requestMap = ConvertFactory.stringToMap(requestString);
			responseMap = Business.getConcreteBusiness(requestMap).perform(requestMap,request,response);
		}catch(Exception e){
			responseMap.put("returnFlag",VariableFactory.FAIL);
			responseMap.put("exceptionMessage",ExceptionUtil.getExceptionString(e));
			responseMap.put("returnTip","common.tip.systemerror");
			try {
				response.getWriter().write(ConvertFactory.mapToString(responseMap));
			} catch (IOException e1) {
				logger.log(Level.WARNING,"",e1);
			}
			logger.log(Level.WARNING,"",e);
		}
	}
	
	private void downloadImage(HttpServletRequest request,HttpServletResponse response){
		ValidateUtil validateUtil = new ValidateUtil();
		Map<String,Object> map = validateUtil.generateValidateImage();
		request.getSession().setAttribute("validateCoder",map.get("validateCoder"));
		BufferedImage buffImg = (BufferedImage)map.get("validateImage");
		response.setHeader("Pragma", "no-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setContentType("image/jpeg"); 
		try{
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(buffImg,"jpeg",sos);
			sos.close();
		}catch(Exception e){
			logger.log(Level.WARNING,"",e);
		}
	}
	
	private void downloadFile(HttpServletRequest request,HttpServletResponse response){
		
	}
}